package com.feidee.data.email.controller;

import com.feidee.data.email.handler.EventRunner;
import com.feidee.data.email.model.EmailProcessParam;
import com.feidee.data.email.model.EmailRequestParam;
import com.feidee.data.email.model.EmailResult;
import com.feidee.data.email.process.EmailProcess;
import com.feidee.data.report.constant.Constant;
import com.uhb.base.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@RequestMapping("/email")
@Controller
public class EmailController extends BaseController {

	@Resource
	private EventRunner runner;

	@Resource
	private EmailProcess emailProcess;

	@RequestMapping("/send")
	@ResponseBody
	public EmailResult execute(EmailRequestParam requestParam) {

		long start = System.currentTimeMillis();
		EmailResult result = null;
		if (!checkAuth(requestParam.getApt(), requestParam.getKey(), Constant.SCRIT)) {
			result = new EmailResult("-001", "you have not the privilages!please check apt and kpi", requestParam);
		}
		if (requestParam.isKill()) {
			emailProcess.kill(requestParam.getEmail_key());
			result = new EmailResult("000", "kill " + requestParam.getEmail_key() + " successfully");
		}
		if (result != null) {
			long end = System.currentTimeMillis();
			requestParam.setCost(end - start);
			requestParam.setRequestName("/email/send.do");
			result.setData(requestParam);
			return result;
		}
		EmailProcessParam processParam = buildProcessParam(requestParam);
		if (requestParam.isSync()) {
			if (emailProcess.isRunning(requestParam.getEmail_key())) {
				result = new EmailResult("-001", "email is running");
			} else {
				emailProcess.putRunningMail(requestParam.getEmail_key());
				if (requestParam.isSendLog()) {
					result = emailProcess.process(processParam, "async");
				} else {
					result = emailProcess.process(processParam, "sync");
				}
				emailProcess.removeRunningMail(requestParam.getEmail_key());
			}
		} else {
			runner.putEvent(processParam);
			runner.runReport();
			result = new EmailResult("000", "Successfully");
		}
		long end = System.currentTimeMillis();
		requestParam.setCost(end - start);
		requestParam.setRequestName("/email/send.do");
		result.setData(requestParam);
		return result;
	}

	private EmailProcessParam buildProcessParam(EmailRequestParam requestParam) {
		EmailProcessParam param = new EmailProcessParam();
		param.setEmail_key(requestParam.getEmail_key());
		param.setOnly_send(requestParam.isOnlySend());
		param.setSend_email(requestParam.isSendEmail());
		return param;
	}
}
